jQuery(function($){
    $.template = function(html,data){
        return doT.template(html).apply(null,[data]);
    }

    $.arrayToObject = function(data) {
        var obj = new Object();
        $.each(data, function(index, item){
            if (item.name) {
                obj[item.name] = item.value;
            }
        });
        return obj;
    }
    
    $.checkUploadSize = function(obj){
        if($(obj).val() != "" && typeof(obj.files) !== "undefined") {
            var file = obj.files[0];
            if(file.size > 2097152){
                alert("请选择小于 2M 的图片");
                event.stopPropagation();
                event.stopImmediatePropagation();
                return false;
            }
        }
    }
    
	$.ajaxPost = function(url, data, success, error, type) {
		if(typeof type == "undefined"){
			type = "json";
		}
		
		$.ajax({
			"type": "POST",
			"url": url,
			"data": data,
			"dataType": type, 
			"success": success,
			"error": error
		});
	}

    $.setLoading = function(box, isHide) {
        if (isHide == 1) {
            $('.loading', box).remove();
        } else {
            box.append('<div class="loading">loading...</div>');
            var offset = box.offset();
            $('.loading', box).css({
                'width' : box.width(),
                'height' : box.height(),
                'position' : 'fixed',
                'z-index' : 99999,
                'background-color' : '#62a8ea',
                'left' : offset.left,
                'top' : offset.top,
                'opacity' : 0.7,
                'text-align' : 'center',
                'color' : 'white',
                'line-height' : box.height()+'px',
                'padding' : 0,
            });
        }
    }

    $.scrollShowFocus = function(element, isforcus) {
        $('html, body').scrollTop(element.offset().top - 150);
        if(typeof isforcus == "undefined" || isforcus){
            element.focus();
        }
    }

    $.imagePreview = function(element, container, placement) {
        if (!element.data('img')) {
            return;
        }

        var options = {
            "html":true,
            "title":function(){
                return '<a href="' + element.data('img') + '" target="_blank"><img src="' + element.data('img') + '" style="max-width:80px; max-height:80px; margin:10px;" /></a>';
            },
            "trigger":"manual"
        };

        if(typeof container != "undefined" && container != null){
            options["container"] = container;
        }

        if(typeof placement == "undefined" || placement == null){
            placement = "auto top";
        }
        options["placement"] = placement;

        element.tooltip(options);

        element.on('shown.bs.tooltip', function () {
            setTimeout(function(){
                element.tooltip('destroy');
            }, 2000);
        })
        element.tooltip('show');
    }

    $.showTooltip = function(element, title, container, placement, time) {
        element.data('tip', title);
        if (typeof element.data('original-title') == "undefined") {
            var options = {
                "title":function(){
                    return element.data('tip');
                },
                "trigger":"manual"
            };

            if(typeof container != "undefined" && container != null){
                options["container"] = container;
            }

            if(typeof placement == "undefined" || placement == null){
                placement = "auto right";
            }
            options["placement"] = placement;

            element.tooltip(options);

            element.on('shown.bs.tooltip', function () {
                if(typeof time == "undefined"){
                    time = 1500;
                }
                setTimeout(function(){
                    element.tooltip('hide');
                }, time);
            })
        }
        element.tooltip('show');
        element.focus();
    }
	
	/**
     * 错误提示
     * @param string   msg    提示内容
     * @param int      width  提示框宽度,默认300
     * @param function func   关闭时回调方法
     */
    $.showError = function(msg,width,func, timeout=2000){
        width = isNaN(parseInt(width)) || parseInt(width) < 300 ? 300 : parseInt(width);
        var errorDiv = '<div id="error-tips-panel" style="padding:20px;line-height:20px;text-align:center;position:fixed;top:-100px;left:50%;margin-left:-'+parseInt(width / 2)+'px;color:white;font-weight:bolder;background-color:#364448;border:2px solid #364448;border-radius:5px;z-index:999999;box-shadow: 3px 3px 5px #364448;"></div>';
        $('body').append(errorDiv);
        $('#error-tips-panel').css('width', width+'px').html(msg).animate({top : '100px'}, 600);
        setTimeout(function(){
            $('#error-tips-panel').remove();
            func();
        }, timeout+600);
        // $('.modal-backdrop').remove();
        // if(typeof width == "undefined"){
        // width = 300;
        // }
        // $("#alertModal .modal-dialog").width(width);
        // $("#alertModal .modal-header").remove();
        // $("#alertModal .modal-body").html(msg);
        // $("#alertModal").modal('show').css('opacity', 1).on('hidden.bs.modal', function (e) {
        // if(typeof func == "function"){
        // func.call(this);
        // }
        // });
        // setTimeout(function(){
        // $("#alertModal").modal('hide');
        // }, timeout);
    }

    /**
     * 成功提示
     * @param string   msg    提示内容
     * @param int      width  提示框宽度,默认300
     * @param function func   关闭时回调方法
     */
    $.showSuccess = function(msg,width,func, timeout=2000){
        width = isNaN(parseInt(width)) || parseInt(width) < 300 ? 300 : parseInt(width);
        var errorDiv = '<div id="success-tips-panel" style="padding:20px;line-height:20px;text-align:center;position:fixed;top:-100px;left:50%;margin-left:-'+parseInt(width / 2)+'px;color:white;font-weight:bolder;background-color:#364448;border:2px solid #364448;border-radius:5px;z-index:999999;box-shadow: 3px 3px 5px #364448;"></div>';
        $('body').append(errorDiv);
        $('#success-tips-panel').css('width', width+'px').html(msg).animate({top : '100px'}, 600);
        setTimeout(function(){
            $('#success-tips-panel').remove();
            func();
        }, timeout+600);
		// if(typeof width == "undefined"){
  //           width = 300;
  //       }
		// $("#alertModal .modal-dialog").width(width);
		// $("#alertModal .modal-title").html('Success Tips');
		// $("#alertModal .modal-body p").html(msg);
		// $("#alertModal").modal('show').on('hidden.bs.modal', function (e) {
		// 	if(typeof func == "function"){
		// 		func.call(this);
		// 	}
		// });
  //       setTimeout(function(){
  //           $("#alertModal").modal('hide');
  //       }, 2000);
    }

    $.showConfirm = function(msg, confirmFunc, cancelFunc, width,title,confirmText) {
        if(typeof width == "undefined"){
            width = 300;
        }
		$("#confirmModal .modal-dialog").width(width);
		$("#confirmModal .modal-title").html(typeof title == "undefined" ? 'Operation Tips' : title);
		$("#confirmModal .modal-body p").html(msg);
		$("#confirmModal .modal-footer .btn-default").click(function(){
			if(typeof cancelFunc == "function"){
                cancelFunc.call(this);
            }
		});
		$("#confirmModal .modal-footer .btn-primary").html(typeof confirmText == "undefined" ? 'Confirm' : confirmText).click(function(){
			if(typeof confirmFunc == "function"){
                confirmFunc.call(this);
            }
		});
		
		$("#confirmModal").modal('show').on('hidden.bs.modal', function (e) {
			if(typeof func == "function"){
				func.call(this);
			}
		});
    }

    $.removeItem = function(obj, url, tip, isTbody){
        $.showConfirm(tip, function(){
            $.post(url, function(result){
                if(result.status){
                    location.reload(true);
                }else{
                    $.showError(result.msg);
                }
            },'json');
        });
    }

    $.formatUrl = function(url) {
        return url.replace('/Base/', '/');
    }

    $.tableMultiOperate = function(table, callback){
        var ids =  new Array();
        $("input:checked[name='key']", table).each(function(){
            if(!$(this).hasClass('disabled')){
                ids.push(parseInt(this.value));
            }
        });
        callback(ids);
    }

    $.removeList = function(obj,id,pk,controller,action){
        var ids =  new Array();
		var box = $(obj).parents('.list-table');
		var table = box.find('.dataTables_scroll').find('.dataTables_scrollBody table');
		if (table.length < 1) {
			table = box.find('table');
		}
		
        if(typeof id == "undefined" || id == ''){
            id = 'checkListTable';
        }
		
        $("input:checked[name='key']", table).each(function(){
            if(!$(this).hasClass('disabled')){
                ids.push(this.value);
            }
        });
		console.log(ids);
        
        ids = ids.join(',');
        if(ids == ''){
            $.showError('Please select the item to be deleted');
            return false;
        }
        $.showConfirm('Are you sure you want to delete it?',function(){
            var query = new Object();
            query.id = ids;

            var url = SITE_URL;
            if(typeof controller == "undefined" || controller == ''){
                controller = CURR_CONTROLLER;
            }
            
            if(typeof action == "undefined" || action == ''){
                action = 'delete';
            }

            if(typeof pk != "undefined"){
                query.pk = pk;
            }

            $.post($.formatUrl(url + '/' + controller + '/' + action), query, function(result){
                if(result.status){
                    location.reload(true);
                }else{
                    $.showError(result.msg);
                }
            },'json');
        });
        return false;
    }

    $.tableCheckHandler = function(obj){
        var checked = obj.checked;
		var table = $(obj).parents('.dataTables_scroll').find('.dataTables_scrollBody table');
		if (table.length < 1) {
			table = $(obj).parents('table');
		}
        $("tbody > tr > td:first-child input",table).each(function(){
            if(!$(this).attr('disabled')){
                if(checked){
                    $(this).parent().addClass("checked");
                }else{
                    $(this).parent().removeClass("checked");
                }
                this.checked = checked;
            }
        });
    }

	$.showModal = function(url,data,btnOk,width,height){
        width = parseInt(width);
        height = parseInt(height);
        var widthStr = width>0?width:680;
        var heightStr = height>0?(height+"px"):"auto";
		$(".modal").modal("hide");
		$("#man-modal-dialog").remove();
		var modalHtml = '<div id="man-modal-dialog" class="modal fade man-modal"><div class="modal-dialog" style="width:'+widthStr+'px;min-height:50px;"><div class="modal-content" style="height:'+heightStr+';">'+
						'<div class="modal-header">Loading...<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button></div>'+
						'</div></div></div>';
		$("body").append(modalHtml);
		$("#man-modal-dialog").modal();
		$('#man-modal-dialog').on('hide.bs.modal', function () {
			modalData = false;
		});

		$.get(url,data,function(tpl){
			$("#man-modal-dialog .modal-dialog .modal-content").html(tpl);
            $(document).off("click","#man-modal-dialog .yz-btn-ok");
			$(document).on('click',"#man-modal-dialog .yz-btn-ok", function () {
				if(typeof(btnOk) == "function")
                    btnOk.call(this,typeof(modalData) != "undefined" ? modalData : "" );
				modalData = false;
				//$("#man-modal-dialog").modal("hide");
			});
		});
	}

    $.toggleStatus = function(obj){
        var data = {};
        var url = SITE_URL + "/" + CURR_CONTROLLER +  "/" + "toggleStatus";
        data.key =  new Array();
        $("input[name=key]").each(function(){
            if($(this).is(":checked")){
                data.key.push(this.value);
            }
        })
        data.key = data.key.join(",");
        if(data.key == ''){
            $.showError('Please select the item');
            return false;
        }
        if(obj.hasClass("btn-activate")){
            data.status = 1;
        }else{
            data.status = 0;
        }
        $.post(url, data, function(res){
            if(!res.status){
                $.showError(res.msg);
            }else{
                $.showSuccess(res.msg,function(){
                    setTimeout(function(){
                        location.reload();
                    },1000);
                })
            }

        })
    }

    $(document).on("click", ".table-status",function(){
        var obj = $(this);
        var data = {};
        data.key = $(this).parents("tr").attr("key");
        data.status = $(this).attr("status");
        data.field = $(this).attr("field");
        var url = SITE_URL + "/" + CURR_CONTROLLER +  "/" + "toggleStatus";
        $.post(url, data,function(res){
            if(!res.status){
                $.showError(res.msg);
            }else{
                if(obj.hasClass("fa-check")){
                    obj.removeClass("fa-check text-success table-status1").addClass("fa-lock table-status0");
                }else{
                    obj.removeClass("fa-lock table-status0").addClass("fa-check text-success table-status1");
                }
            }
        })
    })

    $(document).on("submit",".ajax-form",function(){
        var data = $(this).serialize();
        var id = $(this).find("input[name=id]").val();
        var url = $(this).find("input[name=__RETURN_URL__]").val();
        var postUrl = $(this).attr("action");
        $.post(postUrl, data, function (res) {
            if(!res.status){
                $.showError(res.msg);
            }else{
                if(res.url != ''){
                    url = res.url;
                }
                $.showSuccess(res.msg,function(){
                    setTimeout(function(){
                        location.href = url;
                    },1000)
                });
            }
        })
        return false;
    })
});